package com.chenfan.mcn.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenfan.common.exception.BusinessException;
import com.chenfan.mcn.clients.baseinfo.BaseCustomer;
import com.chenfan.mcn.clients.baseinfo.BaseInfoClient;
import com.chenfan.mcn.clients.baseinfo.DescByCodeDTO;
import com.chenfan.mcn.clients.privilege.PrivilegeClient;
import com.chenfan.mcn.clients.privilege.SDepartment;
import com.chenfan.mcn.constant.BillCodeCst;
import com.chenfan.mcn.enums.ApprovalEnum;
import com.chenfan.mcn.enums.DiscountApprovalEnum;
import com.chenfan.mcn.enums.ApprovalStatusEnum;
import com.chenfan.mcn.dao.DiscountApprovalMapper;
import com.chenfan.mcn.dao.IncomeContractMapper;
import com.chenfan.mcn.dao.YearFrameContractMapper;
import com.chenfan.mcn.enums.IncomeContractTypeEnum;
import com.chenfan.mcn.exception.McnErrorCode;
import com.chenfan.mcn.component.CodeGenerateHelper;
import com.chenfan.mcn.model.*;
import com.chenfan.mcn.model.dto.*;
import com.chenfan.mcn.model.vo.*;
import com.chenfan.mcn.service.*;
import com.chenfan.mcn.utils.BusinessAssert;
import com.chenfan.mcn.utils.CommonUtil;
import com.chenfan.common.extension.util.SmartCompletableFuture;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * <p>
 * 折扣审批单 服务实现类
 * </p>
 *
 * @author lizhejin
 * @since 2021-01-07
 */
@Service
public class DiscountApprovalServiceImpl extends ServiceImpl<DiscountApprovalMapper, DiscountApproval> implements DiscountApprovalService, ApprovalCallbackService {

    @Autowired
    private PrivilegeClient privilegeClient;

    @Autowired
    private BaseInfoClient baseInfoClient;

    @Autowired
    private DiscountRebateService discountRebateService;

    @Autowired
    private PlatformDiscountRangeService platformDiscountRangeService;

    @Autowired
    private IncomeContractMapper incomeContractMapper;

    @Autowired
    private YearFrameContractMapper yearFrameContractMapper;

    @Autowired
    private ApprovalFlowService approvalFlowService;

    @Autowired
    private DiscountApprovalMapper discountApprovalMapper;


    @Override
    public Page<DiscountApprovalVO> getDiscountApprovalList(McnPage<DiscountApprovalVO> page, DiscountApprovalSearchDTO searchDTO) {
        searchDTO.setAlias("da.");
        searchDTO.setProcessId(ApprovalEnum.DISCOUNT_APPROVAL.getProcessId());
        if (Objects.nonNull(searchDTO.getFlowUserId())) {
            List<Long> srcList = approvalFlowService.getSrcList(Lists.newArrayList(searchDTO.getFlowUserId()), searchDTO.getProcessId());
            if (CollectionUtil.isEmpty(srcList)) {
                return new Page<>();
            }
            searchDTO.setDiscountIdList(srcList);
        }
        Page<DiscountApprovalVO> resultPage = baseMapper.selectTableList(page, searchDTO);
        List<Long> flowList = resultPage.getRecords().stream().map(DiscountApprovalVO::getFlowId).filter(Objects::nonNull).collect(Collectors.toList());
        List<Long> customerIdList = resultPage.getRecords().stream().map(DiscountApprovalVO::getCustomerId).distinct().collect(Collectors.toList());
        List<String> dictProfileList = Arrays.asList("SubjectOfContract", "Rebate_type", "Single_platform", "Publishing_platform");
        List<String> dictList = resultPage.getRecords().stream().map(DiscountApprovalVO::getContractSubject).distinct().collect(Collectors.toList());
        List<Long> departmentIdList = resultPage.getRecords().stream().map(DiscountApprovalVO::getDepartmentId).distinct().collect(Collectors.toList());
        dictList.addAll(resultPage.getRecords().stream().map(DiscountApprovalVO::getRebateType).distinct().collect(Collectors.toList()));
        if (Objects.nonNull(searchDTO.getExportStatus()) && searchDTO.getExportStatus()) {
            buildExportParams(dictList, resultPage);
        }
        buildList(dictList, dictProfileList, customerIdList, departmentIdList, resultPage, searchDTO, flowList);
        return resultPage;
    }

    private void buildExportParams(List<String> dictList, Page<DiscountApprovalVO> resultPage) {
        Set<String> platformList = new HashSet<>();
        Set<String> publishList = new HashSet<>();
        String returnChar = "\n";
        resultPage.getRecords().forEach(vo -> {
            if (Objects.nonNull(vo.getRangeInfo())) {
                for (String range : vo.getRangeInfo().split(returnChar)) {
                    platformList.addAll(Arrays.asList(range.split("////")[0].split(",")));
                }
            }
            if (Objects.nonNull(vo.getRebateInfo())) {
                for (String range : vo.getRebateInfo().split(returnChar)) {
                    publishList.addAll(Arrays.asList(range.split("////")[0].split(",")));
                }
            }
        });
        dictList.addAll(platformList);
        dictList.addAll(publishList);
    }

    private void buildList(List<String> dictList, List<String> dictProfileList, List<Long> customerIdList, List<Long> departmentIdList, Page<DiscountApprovalVO> resultPage, DiscountApprovalSearchDTO dto, List<Long> flowList) {
        Map<Long, SDepartment> departmentMapping = null;
        Map<String, String> dictMapping = Objects.requireNonNull(baseInfoClient.getDescByCode(new DescByCodeDTO().setDictsCodes(dictList).setProfileCodes(dictProfileList))).getObj();
        if (departmentIdList.size() > 0) {
            departmentMapping = Objects.requireNonNull(privilegeClient.getDepartmentByIds(departmentIdList)).getObj();
        }
        Map<Long, BaseCustomer> customerMapping = Objects.requireNonNull(baseInfoClient.getMcnCustomerByIds(customerIdList)).getObj();
        JSONObject flowMapping = null;
        if (Objects.nonNull(flowList) && flowList.size() > 0) {
            flowMapping = approvalFlowService.getFlowStatus(flowList);
        }
        if (Objects.nonNull(dictMapping) || Objects.nonNull(customerMapping) || Objects.nonNull(flowMapping)) {
            JSONObject finalFlowMapping = flowMapping;
            Map<Long, SDepartment> finalDepartmentMapping = departmentMapping;
            resultPage.getRecords().forEach(vo -> {
                if (dictMapping.size() > 0) {
                    vo.setContractSubjectName(dictMapping.get(dictProfileList.get(0) + ";" + vo.getContractSubject()));
                    vo.setRebateTypeName(dictMapping.get(dictProfileList.get(1) + ";" + vo.getRebateType()));
                }
                if (customerMapping.size() > 0) {
                    BaseCustomer customer = customerMapping.get(vo.getCustomerId());
                    vo.setCustomerName(Objects.nonNull(customer) ? customer.getCustomerNameC() : "");
                }
                if (finalDepartmentMapping.size() > 0) {
                    SDepartment department = finalDepartmentMapping.get(vo.getDepartmentId());
                    vo.setDepartmentName(Objects.nonNull(department) ? department.getDepartmentName() : "");
                }
                if (Objects.nonNull(dto.getExportStatus()) && dto.getExportStatus()) {
                    vo.setRangeInfo(buildExportResultInfo(vo.getRangeInfo(), dictMapping, dictProfileList.get(3)));
                    vo.setRebateInfo(buildExportResultInfo(vo.getRebateInfo(), dictMapping, dictProfileList.get(2)));
                }
                if (Objects.nonNull(finalFlowMapping) && finalFlowMapping.size() > 0 && Objects.nonNull(vo.getFlowId())) {
                    vo.setFlowStatusName(finalFlowMapping.getString(vo.getFlowId().toString()));
                }
            });
        }
    }

    private String buildExportResultInfo(String info, Map<String, String> dictMapping, String prefix) {
        if (Objects.isNull(info)) {
            return null;
        }
        String returnChar = "\n";
        String[] arrList = info.split(returnChar);
        for (int j = 0; j < arrList.length; j++) {
            String[] infos = arrList[j].split("////");
            String[] rangeParams = infos[0].split(",");
            for (int i = 0; i < rangeParams.length; i++) {
                rangeParams[i] = dictMapping.get(prefix + ";" + rangeParams[i]);
            }
            infos[0] = ArrayUtil.join(rangeParams, "、");
            arrList[j] = ArrayUtil.join(infos, "    ");
        }
        return ArrayUtil.join(arrList, returnChar);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveDiscount(DiscountDTO dto) {
        if (Objects.nonNull(dto.getCommitStatus()) && dto.getCommitStatus()) {
            dto.setApprovalStatus(ApprovalStatusEnum.APPROVAL.code());
        }
        String discountCode;
        if (Objects.isNull(dto.getId())) {
            discountCode = CodeGenerateHelper.getCode(BillCodeCst.DISCOUNT_APPROVAL);
            dto.setDiscountCode(discountCode);
            baseMapper.insert(dto);
        } else {
            DiscountApproval discountApproval = baseMapper.selectById(dto.getId());
            saveVertifyStatus(discountApproval);
            discountCode = discountApproval.getDiscountCode();
            baseMapper.updateById(dto);
            dto.setDiscountCode(discountCode);
            new LambdaUpdateChainWrapper<>(discountRebateService.getBaseMapper()).eq(DiscountRebate::getDiscountId, dto.getId()).remove();
            new LambdaUpdateChainWrapper<>(platformDiscountRangeService.getBaseMapper()).eq(PlatformDiscountRange::getDiscountId, dto.getId()).remove();
        }
        if (Objects.nonNull(dto.getRebateList()) && !dto.getRebateList().isEmpty()) {
            dto.getRebateList().forEach(discountRebate -> {
                discountRebate.setDiscountId(dto.getId());
                discountRebate.setCreateBy(dto.getUpdateBy());
                discountRebate.setCreateName(dto.getUpdateName());
                discountRebate.setUpdateBy(dto.getUpdateBy());
                discountRebate.setUpdateName(dto.getUpdateName());
            });
            discountRebateService.saveBatch(dto.getRebateList());
        }
        if (Objects.nonNull(dto.getRangeList()) && !dto.getRangeList().isEmpty()) {
            dto.getRangeList().forEach(discountRange -> {
                discountRange.setDiscountId(dto.getId());
                discountRange.setCreateBy(dto.getUpdateBy());
                discountRange.setCreateName(dto.getUpdateName());
                discountRange.setUpdateBy(dto.getUpdateBy());
                discountRange.setUpdateName(dto.getUpdateName());
            });
            platformDiscountRangeService.saveBatch(dto.getRangeList());
        }
        if (Objects.nonNull(dto.getCommitStatus()) && dto.getCommitStatus()) {
            approvalFlowService.startProcess(dto.getId(), discountCode, ApprovalEnum.DISCOUNT_APPROVAL, JSON.toJSONString(dto));
        }
        return dto.getId();
    }

    private void saveVertifyStatus(DiscountApproval discountApproval) {

        if (discountApproval.getApprovalStatus() != ApprovalStatusEnum.UN_COMMIT.code() &&
                discountApproval.getApprovalStatus() != ApprovalStatusEnum.REJECTED.code() &&
                discountApproval.getApprovalStatus() != ApprovalStatusEnum.CANCEL.code()) {
            throw new BusinessException(McnErrorCode.DISCOUNT_APPROVA_UPDATE_ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeStatus(DiscountApproval discountApproval) {
        //TODO 校验 是否被合同引用，如果引用了 抛出异常
        DiscountApproval entity = baseMapper.selectById(discountApproval.getId());
        boolean flag = this.updateById(discountApproval);
        if (discountApproval.getApprovalStatus() == ApprovalStatusEnum.APPROVAL.code()) {
            approvalFlowService.startProcess(entity.getId(), entity.getDiscountCode(), ApprovalEnum.DISCOUNT_APPROVAL, JSON.toJSONString(discountApproval));
        }
        if (discountApproval.getApprovalStatus() == ApprovalStatusEnum.CANCEL.code() || discountApproval.getApprovalStatus() == ApprovalStatusEnum.INVALID.code()) {
            approvalFlowService.revokeProcess(discountApproval.getId(), ApprovalEnum.DISCOUNT_APPROVAL.getProcessId());
        }
        return flag;
    }

    @Override
    public DiscountInfoVO getDiscountApprovalInfo(Long id) {
        DiscountInfoVO dto = baseMapper.selectDiscountApproval(id);
        if (Objects.isNull(dto)) {
            throw new BusinessException(McnErrorCode.DISCOUNT_NOT_EXISTS);
        }
        List<Long> customerIdList = new ArrayList<>(Collections.singletonList(dto.getCustomerId()));
        List<String> dictProfileList = new ArrayList<>(Arrays.asList("SubjectOfContract", "Rebate_type", "Single_platform", "Publishing_platform"));
        List<String> dictList = new ArrayList<>(Collections.singletonList(dto.getContractSubject()));
        dictList.add(dto.getRebateType());
        if (Objects.nonNull(dto.getRebateList()) && !dto.getRebateList().isEmpty()) {
            Set<String> rebateDictionary = new HashSet<>();
            for (DiscountRebateVO vo : dto.getRebateList()) {
                rebateDictionary.addAll(Arrays.asList(vo.getOrderPlatformIds().split(",")));
            }
            dictList.addAll(rebateDictionary);
        }
        if (Objects.nonNull(dto.getRangeList()) && !dto.getRangeList().isEmpty()) {
            Set<String> rangeDictionary = new HashSet<>();
            for (PlatformDiscountRangeVO vo : dto.getRangeList()) {
                rangeDictionary.addAll(Arrays.asList(vo.getPlatformIds().split(",")));
            }
            dictList.addAll(rangeDictionary);
        }
        List<Long> departmentIdList = new ArrayList<>(Collections.singletonList(dto.getDepartmentId()));
        Map<String, String> dictMapping = Objects.requireNonNull(baseInfoClient.getDescByCode(new DescByCodeDTO().setDictsCodes(dictList).setProfileCodes(dictProfileList))).getObj();
        Map<Long, BaseCustomer> customerMapping = Objects.requireNonNull(baseInfoClient.getMcnCustomerByIds(customerIdList)).getObj();
        Map<Long, SDepartment> departmentMapping = Objects.requireNonNull(privilegeClient.getDepartmentByIds(departmentIdList)).getObj();
        dto.setContractSubjectName(dictMapping.get(dictProfileList.get(0) + ";" + dto.getContractSubject()));
        dto.setRebateTypeName(dictMapping.get(dictProfileList.get(1) + ";" + dto.getRebateType()));
        if (CommonUtil.containsKey(customerMapping, dto.getCustomerId())) {
            dto.setCustomerName(customerMapping.get(dto.getCustomerId()).getCustomerNameC());
        }
        if (CommonUtil.containsKey(departmentMapping, dto.getDepartmentId())) {
            dto.setDepartmentName(departmentMapping.get(dto.getDepartmentId()).getDepartmentName());
        }
        if (Objects.nonNull(dto.getRebateList()) && !dto.getRebateList().isEmpty()) {
            for (DiscountRebateVO vo : dto.getRebateList()) {
                String[] ids = vo.getOrderPlatformIds().split(",");
                for (int i = 0; i < ids.length; i++) {
                    ids[i] = dictMapping.get(dictProfileList.get(2) + ";" + ids[i]);
                }
                vo.setInfo(ArrayUtil.join(ids, "、"));
            }
        }
        if (Objects.nonNull(dto.getRangeList()) && !dto.getRangeList().isEmpty()) {
            for (PlatformDiscountRangeVO vo : dto.getRangeList()) {
                String[] ids = vo.getPlatformIds().split(",");
                for (int i = 0; i < ids.length; i++) {
                    ids[i] = dictMapping.get(dictProfileList.get(3) + ";" + ids[i]);
                }
                vo.setInfo(ArrayUtil.join(ids, "、"));
            }
        }
        Long flowId = approvalFlowService.getFlowId(id, ApprovalEnum.DISCOUNT_APPROVAL.getProcessId());
        String stringFlowIds = approvalFlowService.getStringFlowIds(id, ApprovalEnum.DISCOUNT_APPROVAL.getProcessId());
        dto.setFlowId(flowId);
        dto.setFlowIds(stringFlowIds);
        if (Objects.nonNull(dto.getFlowId())) {
            JSONObject flowStatus = approvalFlowService.getFlowStatus(Collections.singletonList(dto.getFlowId()));
            if (Objects.nonNull(flowStatus) && flowStatus.size() > 0) {
                dto.setFlowStatusName(flowStatus.getString(dto.getFlowId().toString()));
            }
        }
        return dto;
    }

    @Override
    public int checkYearActiveCounts(DiscountDTO dto) {
        return baseMapper.selectActiveCounts(dto);
    }

    @Override
    public List<DiscountInfoVO> getApprovalConditionally(ApprovalConditionallyDTO approvalConditionallyDTO) {
        List<DiscountInfoVO> discountInfoVOList = new ArrayList<>();


        /**
         *  校验折扣审批单(先查询年度优惠的id)
         */
        ApprovalSearchDTO approvalSearchDTO = new ApprovalSearchDTO();
        approvalSearchDTO.setApprovalStatus(ApprovalStatusEnum.PASSED.code());
        approvalSearchDTO.setApprovalType(DiscountApprovalEnum.YEAR_DISCOUNT.code());
        approvalSearchDTO.setIsActive(Boolean.TRUE);
        approvalSearchDTO.setCustomerId(approvalConditionallyDTO.getCustomerId());
        ContractVerifyVO yearDiscount = baseMapper.verifyContract(approvalSearchDTO);
        IncomeContractTypeEnum contractTypeEnum = IncomeContractTypeEnum.getType(approvalConditionallyDTO.getContractType());
        boolean single = false;
        switch (contractTypeEnum) {
            case ANNNUAL_DISCOUNT_INCOME_CONSTRACT:
            case ANNUAL_DISCOUNT_FORMAL_CONSTRACT:
                boolean judge1 = yearDiscount == null;
                if (judge1) {
                    throw new BusinessException(McnErrorCode.CUSTOMER_HAS_NO_ELIGIBLE_ANNUAL_DISCOUNT);
                }
                break;
            case SINGLE_ORDERS_INCOME_CONSTRACT:
            case SINGLE_ORDERS_FORMAL_CONSTRACT:
                single = true;
                boolean judge2 = yearDiscount != null;
                if (judge2) {
                    throw new BusinessException(McnErrorCode.CUSTOMER_HAS_ELIGIBLE_ANNUAL_DISCOUNT);
                }
                break;
            default:
                ;
        }

        if (!single) {
            DiscountInfoVO yearDiscountInfoVo = new DiscountInfoVO();
            if (yearDiscount != null) {
                yearDiscountInfoVo = this.getDiscountApprovalInfo(yearDiscount.getId());

                /**
                 * 查询审批单关联的生效中的年框合同
                 */
                YearFrameContract yearFrameContract = yearFrameContractMapper.geteffectiveContract(yearDiscount.getId());
                if (yearFrameContract != null) {
                    yearDiscountInfoVo.setYearContractId(yearFrameContract.getId());
                    yearDiscountInfoVo.setYearContractCode(yearFrameContract.getYearFrameCode());
                }
            }
            discountInfoVOList.add(yearDiscountInfoVo);
        }

        /**
         * 查询是否有单笔折扣
         */
        approvalSearchDTO.setApprovalType(DiscountApprovalEnum.SINGLE_DISCOUNT.code());
        approvalSearchDTO.setIncomeContractId(approvalConditionallyDTO.getIncomeContractId());
        List<Long> discountIdList = baseMapper.getDiscountIdList(approvalSearchDTO);
        if (CollectionUtil.isNotEmpty(discountIdList)) {
            //List<CompletableFuture> completableFutureList = new ArrayList<>(discountIdList.size());
            for (Long discountId : discountIdList) {
                //completableFutureList.add(SmartCompletableFuture.runAsync(() -> {
                    DiscountInfoVO discountInfoVO = this.getDiscountApprovalInfo(discountId);
                    discountInfoVOList.add(discountInfoVO);
                //}));
            }
            //SmartCompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[]{})).join();
        }
        return discountInfoVOList;

    }

    /**
     * 年度优惠含平台返点、仅年度优惠：所有合同的商务确认合同金额的总合
     */
    @SneakyThrows
    @Override
    public BigDecimal getWithYearAmount(Long customerId, Long discountId) {
        /**
         * 获取折扣审批单政策开始时间
         */
        DiscountApproval discountApproval = discountApprovalMapper.selectById(discountId);
        Date startTime = DateUtils.parseDate(discountApproval.getStartDate(), "yyyy-MM-dd HH:mm:ss");
        /**
         * 年度优惠含平台返点、仅年度优惠：所有合同的商务确认合同金额的总合
         */
        BigDecimal newestAmount = incomeContractMapper.getWithYearAmount(customerId, startTime, new Date());
        return newestAmount;
    }

    /**
     * 年度优惠不含平台返点：合同类型是“散单-形式合同或者年度优惠-形式合同”的所有合同的商务确认合同金额的总合
     */
    @SneakyThrows
    @Override
    public BigDecimal getWithNoYearAmount(Long customerId, Long discountId) {
        /**
         * 获取折扣审批单政策开始时间
         */
        DiscountApproval discountApproval = discountApprovalMapper.selectById(discountId);
        Date startTime = DateUtils.parseDate(discountApproval.getStartDate(), "yyyy-MM-dd HH:mm:ss");
        BigDecimal newestAmount = incomeContractMapper.getWithNoYearAmount(customerId, startTime, new Date());
        return newestAmount;
    }

    /**
     * 根据客户名称获取折扣返点审批单号(所有类型是【年度优惠】的折扣返点审批单，且状态是审核通过。)
     *
     * @param customerId {@link Long}
     * @return {@link List}
     */
    @Override
    public List<String> getDisCountApprovalCode(Long customerId) {
        return discountApprovalMapper.getDisCountApprovalCode(customerId);
    }

    /**
     * 客户档案关联折扣审批单
     *
     * @param page
     * @param customerId
     * @return
     */
    @Override
    public Page<DiscountApprovalRelationVO> getDiscountApprovalRelationList(McnPage<DiscountApprovalRelationVO> page, Long customerId) {
        Page<DiscountApprovalRelationVO> list = discountApprovalMapper.getDiscountApprovalRelationList(page, customerId);
        List<String> dictProfileList = Collections.singletonList("SubjectOfContract");
        List<String> dictList = list.getRecords().stream().map(DiscountApprovalRelationVO::getContractSubject).distinct().collect(Collectors.toList());
        Map<String, String> dictMapping = Objects.requireNonNull(baseInfoClient.getDescByCode(new DescByCodeDTO().setDictsCodes(dictList).setProfileCodes(dictProfileList))).getObj();
        if (Objects.nonNull(dictMapping)) {
            list.getRecords().forEach(x -> {
                if (dictMapping.size() > 0) {
                    x.setContractSubjectName(dictMapping.get(dictProfileList.get(0) + ";" + x.getContractSubject()));
                }
            });
        }
        return list;
    }

    @Override
    public DiscountApproval getByCode(String discountCode) {
        //无删除功能
        return this.baseMapper.selectOne(Wrappers.lambdaQuery(DiscountApproval.class).eq(DiscountApproval::getDiscountCode, discountCode));
    }

    @Override
    public void approvalCallback(ApprovalFlowDTO approvalFlowDTO, Boolean status) {
        DiscountApproval discountApproval = this.baseMapper.selectById(approvalFlowDTO.getSrcId());
        BusinessAssert.notNull(discountApproval, McnErrorCode.DISCOUNT_NOT_EXISTS);
        approvalFlowDTO.setSrcCode(discountApproval.getDiscountCode());
        approvalFlowDTO.addSubmitInfoIfNull(discountApproval);
        if (Objects.isNull(status)) {
            //审批流配置-接入待办
            return;
        }
        // 当订单是主动撤回 作废时  不再去更新状态
        if (discountApproval.getApprovalStatus() != ApprovalStatusEnum.INVALID.code() && discountApproval.getApprovalStatus() != ApprovalStatusEnum.CANCEL.code()) {
            discountApproval.setApprovalStatus(status ? ApprovalStatusEnum.PASSED.code() : ApprovalStatusEnum.REJECTED.code());
            discountApproval.setUpdateBy(approvalFlowDTO.getUserId());
            discountApproval.setUpdateName(approvalFlowDTO.getUserName());
            discountApproval.setUpdateDate(new Date());
            this.baseMapper.updateById(discountApproval);
            approvalFlowService.sendNotify(approvalFlowDTO, discountApproval.getId(), discountApproval.getDiscountCode()
                    , ApprovalEnum.DISCOUNT_APPROVAL, status, discountApproval.getCreateBy(), discountApproval.getCreateName());
        }
    }
}
